export default function useImageHeight() {
  const imgPromises: Promise<number>[] = [];
  const imgHeights: number[] = [];

  const imgOutEls: HTMLDivElement[] = [];
  const imgSrcs: string[] = [];

  const getItemRef = (el: HTMLDivElement) => {
    if (el) {
      const [img] = el.getElementsByTagName('img');
      imgOutEls.push(el);

      imgPromises.push(
        new Promise(resolve => {
          let image: HTMLImageElement | null = new Image();
          image.src = img.src;

          imgSrcs.push(img.src);

          image.onload = () => {
            resolve(el.offsetHeight);
          };
          image.onerror = () => {
            resolve(el.offsetHeight);
          };
        })
      );

      imgHeights.push(el.offsetHeight);
    }
  };

  return {
    getItemRef,
    // 预加载, 异步获取图片高度
    getItemHeightsAsync: () => Promise.all(imgPromises),
    updateItemHeightAsync: () => {
      imgPromises.length = 0;

      imgOutEls.forEach((el, index) => {
        imgPromises.push(
          new Promise(resolve => {
            let image: HTMLImageElement | null = new Image();
            image.src = imgSrcs[index];

            image.onload = () => {
              resolve(el.offsetHeight);
            };
            image.onerror = () => {
              resolve(el.offsetHeight);
            };
          })
        );
      });

      return Promise.all(imgPromises);
    },
    updateItemHeightsSync: () => imgOutEls.map(el => el.offsetHeight),
    // 同步获取图片高度
    getItemHeightsSync: () => imgHeights
  };
}
